package com.jiaai.controller;

import com.jiaai.util.MD5;
import com.jiaai.util.UploadUtil;
import com.jiaai.util.image.ImageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * Created by Administrator on 2017/7/8.
 */

@Controller
public class DwnloadController {
    private Logger logger= LoggerFactory.getLogger(DwnloadController.class);
    /**
     * 文件下载
     * @param application  应用名称
     * @param directories  目录
     * @param f 图片名称
     * @param q 压缩比例
     * @param s 图片缩放比例
     * @param w 图片宽度
     * @param h 图片高度
     */
    @RequestMapping("/dwnload/img/{application}/{directories}")
    public  void dwnloadImg(
                         @PathVariable("application") String application,
                         @PathVariable(value = "directories",required = false) String directories,
                         @RequestParam("f")String f,
                         @RequestParam(value = "q",required = false,defaultValue = "0.0") float q,
                         @RequestParam(value = "s",required = false,defaultValue = "0.0")float s,
                         @RequestParam(value = "w",required = false,defaultValue = "0")int w,
                         @RequestParam(value = "h",required = false,defaultValue = "0") int h,
                          HttpServletResponse response){

        response.setContentType("image/png");

        try {
            String imgPath= UploadUtil.getFilePath(f,application,directories);
            File file =new File(imgPath);
            if(q<=0&&s<=0&&w<=0&&h<=0){
                writImg(file,response.getOutputStream());
                return;
            }
            StringBuffer cacheBufff=new StringBuffer();
            String cacheFilePath="";
            ImageUtils imageUtils=ImageUtils.fromFile(file);		//设置原图片
            imageUtils.fixedGivenSize(true);
            if(q>0){  //设置压缩比例，默认为0.75
                imageUtils.quality(q);
                cacheBufff.append("&q=");
                cacheBufff.append(q);
            }else{
                if(s>0){//设置生成图片的伸缩比例
                    imageUtils.scale(s);
                    cacheBufff.append("&s=");
                    cacheBufff.append(s);
                }else{
                    if(w>0){//设置生成图片的宽度，高度将以原图片的高度等比例伸缩
                        imageUtils.width(w);
                        cacheBufff.append("&w=");
                        cacheBufff.append(w);
                    }
                    if(h>0){//设置生成图片的高度，宽度将以原图片的宽度等比例伸缩
                        imageUtils.height(h);
                        cacheBufff.append("&h=");
                        cacheBufff.append(h);
                    }
                }
            }
            cacheBufff.append("_");
            cacheBufff.append(f);
            cacheFilePath= new MD5().getMD5ofStr(cacheBufff.toString())+UploadUtil.getExtName(cacheBufff.toString(),'.');
            String chacheDir=UploadUtil.getCacheDir(application,directories);
            File cacheDir=new File(chacheDir);
            File cacheFile=new File(chacheDir+File.separator+cacheFilePath);
            if(!cacheDir.exists()){
                cacheDir.mkdirs();
            }
            if(!cacheFile.exists()){
                imageUtils.toFile(cacheFile);
            }
            writImg(cacheFile,response.getOutputStream());


        }catch (Exception e){
            logger.error("图片下载失败!error:[{}]",e.getMessage());
        }finally {


        }


    }

    private void writImg(File file, OutputStream outputStream){
        FileInputStream inputStream=null;
        OutputStream stream=null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int)file.length()];
            int length = inputStream.read(data);
            stream = outputStream;
            stream.write(data);
        }catch (Exception e){
            logger.error("图片下载失败!error:[{}]",e.getMessage());
        }finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(stream!=null){
                    stream.flush();
                    stream.close();
                }
            }catch (Exception e){

            }
        }
    }
}
